package com.hycat.mail.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.hycat.mail.common.exception.MailException;
import com.hycat.mail.common.model.ExceptionEnum;
import com.hycat.mail.order.dao.OrderAccountDao;
import com.hycat.mail.order.entity.OrderAccount;
import com.hycat.mail.order.service.OrderAccountService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : lzhycat
 * @date : 2022-08-22 17:26
 */
@Service
public class OrderAccountServiceImpl extends ServiceImpl<OrderAccountDao, OrderAccount> implements OrderAccountService {

    @Override
    public void acquire(Long memberId, String lock) {
        Retryer<Integer> retry = RetryerBuilder.<Integer>newBuilder()
                //发送主键错误进行重试
                .retryIfExceptionOfType(DuplicateKeyException.class)
                //重调策略
                .withWaitStrategy(WaitStrategies.fixedWait(1000, TimeUnit.MILLISECONDS))
                //尝试次数
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .build();

        try {
            retry.call(() -> {
                save(new OrderAccount().from(memberId, lock));
                return null;
            });
        } catch (Exception e) {
            throw new MailException(ExceptionEnum.ORDER_CLICK_TO_FAST);
        }
    }

    @Override
    public void release(Long memberId) {
        removeById(new QueryWrapper<>().eq("member_id", memberId));
    }
}
